package com.zjl.spring.第06章_事务.spring;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Repository
public class BankDaoImpl implements  BankDao{
    @Autowired
    JdbcTemplate jdbcTemplate;


    @Override
    public void plusMoney(String username,BigDecimal range) {
        String sql = "update bank set money=money+? where username=?";
        Object[] args = {range,username};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    @Override
    public void reduceMoney(String username, BigDecimal range) {
        String sql = "update bank set money=money-? where username=?";
        Object[] args = {range,username};
        int update = jdbcTemplate.update(sql, args);
        System.out.println(update);
    }

    @Override
    public List<Map<String, Object>> query() {
        String sql = "select * from bank";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    @Override
    public List<Bank> queryBank() {
        String sql = "select * from bank";
        List<Bank> banks =  jdbcTemplate.query(sql,
                (re,rowName)-> new Bank(re.getString("username"),re.getBigDecimal("money"))
        );
        List<Bank> banks2 =  jdbcTemplate.query(sql,new BeanPropertyRowMapper<>(Bank.class));
        System.out.println(banks2);

        String sql2 = "select count(*) from bank";
        Integer integer = jdbcTemplate.queryForObject(sql2, Integer.class);
        System.out.println("一共有" + integer + "条记录");

        return banks;
    }

}